<template>
	<div class="wrapper">
		<!-- 顶部应用栏 -->
		<header class="mdc-top-app-bar">
			<div class="mdc-top-app-bar__row">
				<section class="mdc-top-app-bar__section mdc-top-app-bar__section--align-start">
					<BackButton />
					<h1 class="mdc-top-app-bar__title">钱包借贷</h1>
				</section>
			</div>
		</header>

		<!-- 借贷金额输入 -->
		<div class="loan-form">
			<!-- 钱包信息显示 -->
			<div class="wallet-info-card" v-if="walletInfo">
				<div class="info-item">
					<span class="info-label">透支额度</span>
					<span class="info-value">¥{{ walletInfo.overdraftAmount || '0.00' }}</span>
				</div>
				<div class="info-item" v-if="parseFloat(walletInfo.currentOverdraftAmount || 0) > 0">
					<span class="info-label">当前透支</span>
					<span class="info-value overdraft">¥{{ walletInfo.currentOverdraftAmount || '0.00' }}</span>
				</div>
				<div class="info-item">
					<span class="info-label">可用借贷额度</span>
					<span class="info-value available">¥{{ availableLoanAmount }}</span>
				</div>
			</div>

			<div class="form-group">
				<label>借贷金额</label>
				<div class="input-wrapper">
					<span class="currency">¥</span>
					<input 
						type="number" 
						v-model="amount" 
						placeholder="请输入借贷金额"
						@input="validateAmount"
						min="0"
						step="0.01"
					/>
				</div>
				<p class="hint" v-if="dailyInterestRate > 0">
					预计每日利息：¥{{ estimatedDailyInterest }}
				</p>
				<p class="warning" v-if="amount && !isNaN(parseFloat(amount)) && parseFloat(amount) > 0 && parseFloat(amount) > parseFloat(availableLoanAmount) && parseFloat(availableLoanAmount) > 0">
					借贷金额超过可用额度
				</p>
			</div>

			<!-- 快捷金额选择 -->
			<div class="quick-amounts">
				<h3 class="section-title">快捷金额</h3>
				<div class="amount-buttons">
					<button 
						v-for="quickAmount in quickAmounts" 
						:key="quickAmount"
						class="amount-btn"
						:class="{ active: amount == quickAmount }"
						@click="selectAmount(quickAmount)"
						:disabled="quickAmount > parseFloat(availableLoanAmount)"
					>
						¥{{ quickAmount }}
					</button>
				</div>
			</div>

			<!-- 借贷说明 -->
			<div class="loan-info">
				<h3 class="section-title">借贷说明</h3>
				<ul>
					<li>借贷金额最低{{ minLoanAmount }}元</li>
					<li v-if="dailyInterestRate > 0">每日利率：{{ (dailyInterestRate * 100).toFixed(3) }}%</li>
					<li>借贷成功后，金额将立即到账</li>
					<li>请及时还款，避免产生更多利息</li>
					<li>借贷金额不能超过可用透支额度</li>
				</ul>
			</div>

			<!-- 提交按钮 -->
			<div class="submit-section">
				<button 
					type="button"
					class="submit-btn" 
					@click.stop="submitLoan" 
					:disabled="!isValidAmount || loading"
					:style="{ cursor: (!isValidAmount || loading) ? 'not-allowed' : 'pointer' }"
					:title="!isValidAmount ? getDisabledReason() : ''"
				>
					<span v-if="loading">处理中...</span>
					<span v-else>确认借贷 ¥{{ amount || '0.00' }}</span>
				</button>
				<!-- 调试信息（开发时可见） -->
				<p v-if="!isValidAmount && amount" class="debug-hint" style="font-size: 2.5vw; color: #999; margin-top: 2vw;">
					提示：{{ getDisabledReason() }}
				</p>
			</div>
		</div>

		<!-- 底部菜单部分 -->
		<AppFooter></AppFooter>
	</div>
</template>

<script>
	import AppFooter from '../components/AppFooter.vue';
	import BackButton from '../components/BackButton.vue';
	export default {
		name: 'WalletLoan',
		data() {
			return {
				amount: '',
				loading: false,
				quickAmounts: [100, 200, 500, 1000],
				dailyInterestRate: 0.001, // 默认0.1%
				minLoanAmount: 100,
				maxLoanAmount: 1000,
				walletInfo: null,
				user: null
			}
		},
		computed: {
			isValidAmount() {
				// 如果没有输入金额，返回false
				const amountStr = (this.amount ?? '').toString();
				if (amountStr.trim() === '') return false;
				
				const num = parseFloat(amountStr);
				// 如果金额无效或小于等于0，返回false
				if (isNaN(num) || num <= 0) return false;
				
				// 如果金额小于最小借贷金额，返回false
				if (num < this.minLoanAmount) return false;
				
				const available = parseFloat(this.availableLoanAmount);
				// 如果可用额度小于等于0，返回false
				if (available <= 0) return false;
				
				// 如果金额大于可用额度，返回false
				if (num > available) return false;
				
				return true;
			},
			availableLoanAmount() {
				// 即使walletInfo未加载，也使用默认值计算可用额度
				let overdraft = 0;
				let current = 0;
				
				if (this.walletInfo) {
					// 解析透支额度（可能是字符串格式如 "0.00"）
					overdraft = parseFloat(this.walletInfo.overdraftAmount || '0') || 0;
					// 解析当前透支金额
					current = parseFloat(this.walletInfo.currentOverdraftAmount || '0') || 0;
				}
				
				// 如果透支额度为0或未设置，使用规则配置的最大透支额度或默认值500
				if (overdraft <= 0) {
					// 优先使用规则配置的最大透支额度，如果还没有加载完成，使用默认值500
					overdraft = (this.maxLoanAmount > 0) ? this.maxLoanAmount : 500;
				}
				
				// 计算可用额度：透支额度 - 当前透支金额
				const available = Math.max(0, overdraft - current);
				return available.toFixed(2);
			},
			estimatedDailyInterest() {
				const num = parseFloat(this.amount);
				if (isNaN(num) || num <= 0) return '0.00';
				const interest = num * this.dailyInterestRate;
				return interest.toFixed(2);
			}
		},
		created() {
			let user = this.$getSessionStorage('user');
			if (user == null) {
				this.$router.push('/login');
				return;
			}
			this.user = user;
			this.loadWalletInfo();
			this.loadLoanRules();
		},
		methods: {
			loadWalletInfo() {
				this.$axios.post('wallet/info', this.$qs.stringify({
					walletId: this.user.userId
				})).then(response => {
					if (response.data && (response.data.code === 200 || response.data.code === '200')) {
						const result = response.data.result || {};
						// 确保所有字段都有默认值
						this.walletInfo = {
							walletId: result.walletId || this.user.userId,
							balance: result.balance || '0.00',
							frozenAmount: result.frozenAmount || '0.00',
							availableBalance: result.availableBalance || '0.00',
							isVIP: result.isVIP || false,
							isAllowedOverdraft: result.isAllowedOverdraft || false,
							overdraftAmount: result.overdraftAmount || '0.00',
							currentOverdraftAmount: result.currentOverdraftAmount || '0.00'
						};
					}
				}).catch(error => {
					console.error('获取钱包信息失败:', error);
					this.$toast?.error('获取钱包信息失败');
					// 设置默认值，避免计算错误
					this.walletInfo = {
						walletId: this.user.userId,
						balance: '0.00',
						frozenAmount: '0.00',
						availableBalance: '0.00',
						isVIP: false,
						isAllowedOverdraft: false,
						overdraftAmount: '0.00',
						currentOverdraftAmount: '0.00'
					};
				});
			},
			loadLoanRules() {
				// 从后端获取透支规则（利息率等）
				this.$axios.post('WalletRuleController/getRechargeRule').then(response => {
					if (response.data && (response.data.code === 200 || response.data.code === '200') && response.data.result) {
						const rule = response.data.result;
						this.dailyInterestRate = parseFloat(rule.dailyInterestRate || 0.001);
						this.minLoanAmount = parseFloat(rule.minOverdraftAmount || 100);
						this.maxLoanAmount = parseFloat(rule.maxOverdraftAmount || 1000);
					}
				}).catch(error => {
					console.error('获取借贷规则失败:', error);
				});
			},
			selectAmount(amount) {
				const available = parseFloat(this.availableLoanAmount);
				if (available <= 0) {
					this.$toast?.error('当前无可借贷额度');
					return;
				}
				if (amount > available) {
					this.$toast?.error('借贷金额超过可用额度');
					return;
				}
				this.amount = amount.toString();
				this.validateAmount();
			},
		validateAmount() {
			if (!this.amount) return;
			const num = parseFloat(this.amount);
			// 只在金额明显错误时才显示提示，避免频繁提示
			if (num < this.minLoanAmount && num > 0) {
				// 只在金额大于0但小于最小值时提示
				// this.$toast?.error(`借贷金额不能少于${this.minLoanAmount}元`);
			} else if (num > parseFloat(this.availableLoanAmount) && this.availableLoanAmount > 0) {
				// 只在可用额度大于0但输入金额超过时才提示
				// this.$toast?.error('借贷金额超过可用额度');
			}
		},
			getDisabledReason() {
				const amountStr = (this.amount ?? '').toString();
				if (amountStr.trim() === '') {
					return '请输入借贷金额';
				}
				const num = parseFloat(amountStr);
				if (isNaN(num) || num <= 0) {
					return '请输入有效的借贷金额';
				}
				if (num < this.minLoanAmount) {
					return `借贷金额不能少于${this.minLoanAmount}元`;
				}
				const available = parseFloat(this.availableLoanAmount);
				if (available <= 0) {
					return '当前无可借贷额度';
				}
				if (num > available) {
					return `借贷金额超过可用额度（可用额度：¥${available}）`;
				}
				return '金额验证通过';
			},
			submitLoan(event) {
				// 阻止默认行为和事件冒泡
				if (event) {
					event.preventDefault();
					event.stopPropagation();
				}
				
				if (!this.amount || this.loading) {
					if (!this.amount) {
						this.$toast?.error('请输入借贷金额');
					}
					return false;
				}

				const loanAmount = parseFloat(this.amount);
				if (isNaN(loanAmount) || loanAmount <= 0) {
					this.$toast?.error('请输入有效的借贷金额');
					return false;
				}

				if (loanAmount < this.minLoanAmount) {
					this.$toast?.error(`借贷金额不能少于${this.minLoanAmount}元`);
					return false;
				}

				const available = parseFloat(this.availableLoanAmount);
				if (available <= 0) {
					this.$toast?.error('当前无可借贷额度，请先设置透支额度');
					return false;
				}

				if (loanAmount > available) {
					this.$toast?.error(`借贷金额超过可用额度（可用额度：¥${available}）`);
					return false;
				}

				if (!this.user || !this.user.userId) {
					this.$toast?.error('用户信息错误，请重新登录');
					this.$router.push('/login');
					return false;
				}

				// 跳转到借贷支付页面
				this.$router.push({
					path: '/loanPayment',
					query: {
						amount: loanAmount.toFixed(2)
					}
				}).catch(err => {
					console.error('路由跳转失败:', err);
					this.$toast?.error('跳转失败');
				});
				
				return false;
			}
		},
		components: {
			AppFooter,
			BackButton
		}
	}
</script>

<style scoped>
	/****************** 总容器 ******************/
	.wrapper {
		width: 100%;
		min-height: 100vh;
		background-color: #f5f5f5;
	}

	/* 顶部应用栏 */
	.mdc-top-app-bar {
		background-color: #1976D2;
		color: white;
		position: sticky;
		top: 0;
		z-index: 100;
		box-shadow: 0 2px 4px rgba(0,0,0,0.1);
	}

	.mdc-top-app-bar__row {
		display: flex;
		align-items: center;
		height: 72px;
		padding: 0 20px;
	}

	.mdc-top-app-bar__section {
		display: flex;
		align-items: center;
		gap: 16px;
		flex-direction: row;
	}

	.mdc-top-app-bar__title {
		font-size: 22px;
		font-weight: 500;
		margin: 0;
		white-space: nowrap;
		line-height: 1;
	}

	/****************** 借贷表单 ******************/
	.loan-form {
		margin-top: 0;
		padding: 4vw;
	}

	/****************** 钱包信息卡片 ******************/
	.wallet-info-card {
		background: linear-gradient(135deg, #FF9800 0%, #FF5722 100%);
		border-radius: 12px;
		padding: 4vw;
		margin-bottom: 4vw;
		box-shadow: 0 2px 8px rgba(0,0,0,0.1);
		color: #fff;
	}

	.info-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 2.5vw 0;
		border-bottom: 1px solid rgba(255, 255, 255, 0.2);
	}

	.info-item:last-child {
		border-bottom: none;
	}

	.info-label {
		font-size: 3.5vw;
		opacity: 0.9;
	}

	.info-value {
		font-size: 4.5vw;
		font-weight: 600;
	}

	.info-value.overdraft {
		color: #ffd700;
	}

	.info-value.available {
		color: #4CAF50;
	}

	.form-group {
		background-color: #fff;
		border-radius: 12px;
		padding: 4vw;
		margin-bottom: 4vw;
		box-shadow: 0 2px 8px rgba(0,0,0,0.1);
	}

	.form-group label {
		display: block;
		font-size: 3.5vw;
		color: #666;
		margin-bottom: 3vw;
	}

	.input-wrapper {
		display: flex;
		align-items: center;
		border: 2px solid #e0e0e0;
		border-radius: 8px;
		padding: 3vw;
		transition: border-color 0.3s;
	}

	.input-wrapper:focus-within {
		border-color: #FF9800;
	}

	.currency {
		font-size: 5vw;
		color: #333;
		margin-right: 2vw;
		font-weight: 500;
	}

	.input-wrapper input {
		flex: 1;
		border: none;
		outline: none;
		font-size: 6vw;
		color: #333;
	}

	.hint {
		margin-top: 2vw;
		font-size: 3vw;
		color: #ff9800;
	}

	.warning {
		margin-top: 2vw;
		font-size: 3vw;
		color: #f44336;
	}

	/****************** 快捷金额 ******************/
	.quick-amounts {
		background-color: #fff;
		border-radius: 12px;
		padding: 4vw;
		margin-bottom: 4vw;
		box-shadow: 0 2px 8px rgba(0,0,0,0.1);
	}

	.section-title {
		font-size: 4vw;
		color: #666;
		margin: 0 0 3vw 0;
		font-weight: 500;
	}

	.amount-buttons {
		display: flex;
		flex-wrap: wrap;
		gap: 2vw;
	}

	.amount-btn {
		flex: 1;
		min-width: calc(33.33% - 2vw);
		padding: 3vw;
		border: 2px solid #e0e0e0;
		border-radius: 8px;
		background-color: #fff;
		color: #333;
		font-size: 4vw;
		cursor: pointer;
		transition: all 0.3s;
	}

	.amount-btn.active {
		border-color: #FF9800;
		background-color: #FF9800;
		color: #fff;
	}

	.amount-btn:disabled {
		opacity: 0.5;
		cursor: not-allowed;
	}

	.amount-btn:active:not(:disabled) {
		transform: scale(0.95);
	}

	/****************** 借贷说明 ******************/
	.loan-info {
		background-color: #fff;
		border-radius: 12px;
		padding: 4vw;
		margin-bottom: 4vw;
		box-shadow: 0 2px 8px rgba(0,0,0,0.1);
	}

	.loan-info ul {
		margin: 0;
		padding-left: 5vw;
	}

	.loan-info li {
		font-size: 3.5vw;
		color: #666;
		line-height: 1.8;
		margin-bottom: 1.5vw;
	}

	/****************** 提交按钮 ******************/
	.submit-section {
		padding: 4vw;
	}

	.submit-btn {
		width: 100%;
		padding: 4vw;
		background: linear-gradient(135deg, #FF9800 0%, #FF5722 100%);
		color: #fff;
		border: none;
		border-radius: 12px;
		font-size: 4.5vw;
		cursor: pointer;
		transition: all 0.3s;
		box-shadow: 0 4px 12px rgba(255, 152, 0, 0.4);
	}

	.submit-btn:disabled {
		opacity: 0.6;
		cursor: not-allowed;
	}

	.submit-btn:active:not(:disabled) {
		transform: scale(0.98);
	}
</style>


